/**
 * Sample
 * <p/>
 * User: joakimd
 * Date: 2013-04-12
 * Time: 11:11
 */
package org.dru.masic.trix {
import flash.media.Sound;
import flash.utils.ByteArray;

public class Sample implements ISample {
    private var _length: int;
    private var _left: Vector.<Number>;
    private var _right: Vector.<Number>;
    private var _offset:int;

    public function Sample(sound: Sound) {
        var index:int;
        const data: ByteArray = new ByteArray();
        const length: int = sound.length * 44.1;
        sound.extract(data, length);
        _length = length;
        _left = new Vector.<Number>(_length, true);
        _right = new Vector.<Number>(_length, true);
        data.position = 0;
        for (index = 0; index < _length; index++) {
            _left[index] = data.readFloat();
            _right[index] = data.readFloat();
        }
        for (index = 0; index < _length; index++) {
            if (_left[index] != 0.0 || _right[index] != 0.0) {
                _offset = index;
                break;
            }
        }
    }

    public function get length(): int {
        return _length;
    }

    public function copyTo(position: int, left: Vector.<Number>, right: Vector.<Number>, start: int, end: int): void {
        var length: int = end - start;
        do
        {
            var amount: int = Math.min(length, _length - position);
            for (var offset: int = 0; offset < amount; offset++) {
                left[start + offset] = _left[position + offset];
                right[start + offset] = _right[position + offset];
            }
            start += amount;
            position += amount;
            length -= amount;
            if (position == _length) {
                position = 0;
            }
        }
        while (length > 0);
    }

    public function addTo(position: int, left: Vector.<Number>, right: Vector.<Number>, start: int, end: int): void {
        var length: int = end - start;
        do
        {
            var amount: int = Math.min(length, _length - position - _offset);
            for (var offset: int = 0; offset < amount; offset++) {
                left[start + offset] += _left[position + offset + _offset];
                right[start + offset] += _right[position + offset + _offset];
            }
            start += amount;
            position += amount;
            length -= amount;
            if (position + _offset == _length) {
                position = 0;
            }
        }
        while (length > 0);
    }
}
}
